email
module是用來分析及產生MIME Text的內容,但實際要送出email需要靠smtplib
In [25]:
title = u'Title'
recipients = [u'banyhung@patentcloud.com']
sender = u'noreply@patentcloud.com'
subject = u'Test subject'
body = u'你好'
server = '10.60.94.110'
In [26]:
import smtplib
from email.mime.text import MIMEText # 產生 MIME Text
from email.utils import COMMASPACE, formatdate
# 直接由字串產生 MIME Text
msg = MIMEText(body, _charset='utf-8')
# 如果要從檔案中讀取
# with open(textfile, 'rb') as fp:
# msg = MIMEText(fp.read())
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = COMMASPACE.join(recipients)
msg['Date'] = formatdate(localtime=True)
s = smtplib.SMTP(server)
s.sendmail(sender, recipients, msg.as_string())
s.quit()
Out[26]:
In [27]:
print msg.as_string()
In [19]:
from email.parser import Parser
headers = Parser().parsestr(msg.as_string())
print headers['to']
print headers['from']
print headers['subject']
print headers['Content-Transfer-Encoding']
In [32]:
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from os import listdir
In [42]:
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = COMMASPACE.join(recipients)
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(body, _charset='utf-8'))
for filename in [fn for fn in listdir('.') if fn.endswith('ipynb')]:
with open(filename, "rb") as fp:
msg.attach(MIMEApplication(fp.read(),
Content_Disposition='attachment; filename="%s"' % filename,
Name=filename ))
s = smtplib.SMTP(server)
s.sendmail(sender, recipients, msg.as_string())
s.close()
In [ ]: